package middleware

import (
	"log/slog"

	"github.com/gin-gonic/gin"

	v1 "torler.com/qingyue/apps/backend/internal/transport/http/v1"
	"torler.com/qingyue/pkg/jwt"
)

func StrictAuth(j *jwt.JWT, logger *slog.Logger) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.Request.Header.Get("Authorization")
		if tokenString == "" {
			logger.WarnContext(ctx, "No token",
				slog.Any("data", map[string]any{
					"url":    ctx.Request.URL,
					"params": ctx.Params,
				}),
			)
			v1.NewRsp(ctx).WithMsg(v1.ErrUnauthorized).Send()
			ctx.Abort()
			return
		}

		claims, err := j.ParseToken(tokenString)
		if err != nil {
			logger.ErrorContext(ctx, "token error",
				slog.Any("data", map[string]any{
					"url":    ctx.Request.URL,
					"params": ctx.Params,
				}),
				slog.String("error", err.Error()),
			)
			v1.NewRsp(ctx).WithMsg(v1.ErrUnauthorized).Send()
			ctx.Abort()
			return
		}

		ctx.Set("claims", claims)
		recoveryLoggerFunc(ctx, logger)
		ctx.Next()
	}
}

func NoStrictAuth(j *jwt.JWT, logger *slog.Logger) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		tokenString := ctx.Request.Header.Get("Authorization")
		if tokenString == "" {
			tokenString, _ = ctx.Cookie("accessToken")
		}
		if tokenString == "" {
			tokenString = ctx.Query("accessToken")
		}
		if tokenString == "" {
			ctx.Next()
			return
		}

		claims, err := j.ParseToken(tokenString)
		if err != nil {
			ctx.Next()
			return
		}

		ctx.Set("claims", claims)
		recoveryLoggerFunc(ctx, logger)
		ctx.Next()
	}
}

func recoveryLoggerFunc(ctx *gin.Context, logger *slog.Logger) {
	if claims, ok := ctx.MustGet("claims").(*jwt.AuthClaims); ok {
		// Update the logger in context with user_id
		ctxLogger := logger.With(
			"user_id", claims.UserId,
		)
		ctx.Set("logger", ctxLogger)
	}
}
